import { sys } from "cc";

export interface GameStorageData {
    CurrentLevel: number;
    unlock_list_role: number[];
    unlock_map: any[];
    guide_index: number;
    isShowWujin;
    wujin_data;
    free_ad;
}

/** 存储类，用于存储需要本地保存的数据 */
class GameStorage {
    data: GameStorageData = null;
    defaultValue: GameStorageData = null;

    private static _instance: GameStorage = null;

    static get instance(): GameStorage {
        this._instance = this._instance || new GameStorage();
        return this._instance;
    }

    initData() {
        this.InitDefaultData();

        let dataStr = sys.localStorage.getItem(`TileTris_GameStorage`);
        if (!dataStr || dataStr === "") {
            this.clearData();
        } else {
            this.data = JSON.parse(dataStr);
            this.saveData();
        }

        this.SetEveryData();
    }

    // 初始化默认值
    InitDefaultData() {
        this.defaultValue = {
            CurrentLevel: 0,
            unlock_list_role: [],
            unlock_map: [],
            guide_index: 1,
            isShowWujin: false,
            wujin_data: null,
            free_ad: 0,
            // wujin_data: {
            //     u: [],
            //     m: [],
            //     level: 0,
            // },
        };
    }

    SetEveryData() {
        for (let key in this.defaultValue) {
            let defaultValue = this.defaultValue[key];
            let dataValue = this.data[key];
            // console.log(key, defaultValue, dataValue);
            if (dataValue === null || dataValue === undefined) {
                this.data[key] = defaultValue;
            }
        }
        this.saveData();
    }

    clearData() {
        this.data = { ...this.defaultValue };
    }

    saveData() {
        let dataStr = JSON.stringify(this.data);
        sys.localStorage.setItem(`TileTris_GameStorage`, dataStr);
    }
}

export default GameStorage.instance;

/** 调试 */
window["GameStorage"] = GameStorage.instance;
// window['GameStorage'] = GameStorage;